package sniff.diller;

import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
import sniff.pack.MyTCPPacket;
import util.ByteUtil;
import util.InfoUtil;

public class TCPPacketDiller {
	public static MyTCPPacket dill(Packet pack) {
		byte[] head = pack.header;
		int startIndex=34;
		if(((IPPacket) pack).version == 4) {
			startIndex=34;
		}else if(((IPPacket) pack).version == 6){
			startIndex=54;
		}else {
			System.out.println("!!!!!!!!!!!!!!!error TCPPacketDiller");
			return null;
		}
		int sourctPort = ByteUtil.unionByte(head[startIndex], head[startIndex+1]);
		int destinationPort = ByteUtil.unionByte(head[startIndex+2], head[startIndex+3]);
		long seqNum = ByteUtil.unionByte(head[startIndex+4], head[startIndex+5], head[startIndex+6], head[startIndex+7]);// 38 39 40 41
		long ackNum = ByteUtil.unionByte(head[startIndex+8], head[startIndex+9], head[startIndex+10], head[startIndex+11]);// 42 43 44 45
		int dataMigration = ByteUtil.getFourBit(head[startIndex+12], false);
		String keep = getKeep(head[46], head[startIndex+13]);
		int urg = ByteUtil.getIndexBit(head[startIndex+13], 5);
		int ack = ByteUtil.getIndexBit(head[startIndex+13], 4);
		int psh = ByteUtil.getIndexBit(head[startIndex+13], 3);
		int rst = ByteUtil.getIndexBit(head[startIndex+13], 2);
		int syn = ByteUtil.getIndexBit(head[startIndex+13], 1);
		int fin = ByteUtil.getIndexBit(head[startIndex+13], 0);
		int windowSize = ByteUtil.unionByte(head[startIndex+14], head[startIndex+15]);
		String checkNum = "0x" + ByteUtil.byteToHexString(head[startIndex+16]) + ByteUtil.byteToHexString(head[startIndex+17]);
		String urgentPoint = "0x" + ByteUtil.byteToHexString(head[startIndex+18]) + ByteUtil.byteToHexString(head[startIndex+19]);
		String padding = getPadding(head,startIndex);
		MyTCPPacket tcpPack = new MyTCPPacket(sourctPort, destinationPort, seqNum, ackNum, dataMigration, keep, urg,
				ack, psh, rst, syn, fin, windowSize, checkNum, urgentPoint, padding);
		String info = InfoUtil.getTCPInfo(tcpPack);
		tcpPack.setInfo(info);
		if(pack.data.length>0&&HTTPPacketDiller.isHttpPacket(pack)) {
			tcpPack.setChildPacket(HTTPPacketDiller.dill(pack));
		}
		return tcpPack;
	}

	private static String getKeep(byte b1, byte b2) {
		String s = "";
		for (int i = 3; i >= 0; i--) {
			s += ByteUtil.getIndexBit(b1, i);
		}
		s += ByteUtil.getIndexBit(b2, 7);
		s += ByteUtil.getIndexBit(b2, 6);
		return s;
	}

	private static String getPadding(byte[] head,int startIndex) {
		String s = "";
		for (int i = startIndex+20; i < head.length; i++) {
			s += ByteUtil.byteToHexString(head[i]);
		}
		return s;
	}
}
